package order

import (
	"context"
	"parking-lot-go-push/model"
	"parking-lot-go-push/mongodb"
	"time"

	"go.mongodb.org/mongo-driver/bson"
)

type OrderParknflyStruct struct {
	Id                   int       `gorm:"type:int(11) auto_increment; NOT NULL; primary_key"`
	Mobile               string    `gorm:"type:varchar(255); COMMENT:'手机号'"`
	OrderNo              string    `gorm:"type:varchar(255); COMMENT:'系统单号'"`
	ParknflyOrderNo      int       `gorm:"type:int(11); COMMENT:'泊安飞单号'"`
	ReservationStartTime time.Time `gorm:"type:datetime; COMMENT:'预约开始时间'"`
	ReservationEndTime   time.Time `gorm:"type:datetime; COMMENT:'预约结束时间'"`
	Status               int       `gorm:"type:tinyint(1); COMMENT:'订单状态 0 预约中, 1在场地内  2已结束'"`
	Abnormal             int       `gorm:"type:int(11); COMMENT:'异常订单'"`
	CreatedAt            time.Time `gorm:"type:datetime"`
	UpdatedAt            time.Time `gorm:"type:datetime"`
}

func (c *OrderParknflyStruct) TableName() string {
	return "order_parknfly"
}

// 获取订单
func (c *OrderParknflyStruct) FetchOrder(orderNo string, status int) (OrderParknflyStruct, error) {

	var orderParknflyStruct OrderParknflyStruct

	result := model.Db.Table(c.TableName()).
		Where("order_no", orderNo).
		Where("status", status).
		First(&orderParknflyStruct)

	if result.RowsAffected == 0 {
		//删除mongdb记录
		ctx := context.TODO()
		var carsOutMongoDb mongodb.CarsOutMongoDbStruct
		model.MongoDb.Collection(carsOutMongoDb.MongoDBTableName()).DeleteMany(ctx, bson.M{"order_no": orderNo})
	}

	if result.Error != nil {
		return orderParknflyStruct, result.Error
	}

	return orderParknflyStruct, nil
}
